import json
import os
import time

### 初始化一个合规的json文件
def UserInit():
    data = {'1234567890':{'password':'12345678',"money":5000,"ID":1234567890},"Tel":1234567890}
    with open('Bank.txt','w') as f:
        json.dump(data,f)
        
        
### 

def GetUserData():

    with open('Bank.txt','r') as f:
        data = json.load(f)
    #UserSet = set(data.keys())


            
    return data

def GetUserInfo():
    username = input("Please enter your ATM Username:  ").strip()
    password = input("Please enter your ATM Password:  ").strip()
    ID  =  input("Please enter your ID for password recovery :  ").strip()
    Tel =  input("Please enter your Tel for password recovery:  ").strip()
    return username,password,ID,Tel # 返回是一个元组
    
def CreateUserAccount():

    flag = True
    while flag:
        UserSet = set(GetUserData().keys())# 放在这里是因为每次创建成功后需要更新帐号列表
        # 
        print(UserSet)
        print('*' * 30)
        print("请输入对应信息来创建银行帐号，注意不能与现存银行帐号重复")
        username,password,ID,Tel = GetUserInfo()
        if username not in UserSet:
            print("用户帐号可用，准备注册中。。。")
            print(".....")
            WriteData(username,password,ID,Tel)
            print("按Q退出注册程序，按其他键继续创建帐号")
            choice = input("Please enter choice:  ").strip()
            if choice in {'Q','q'}:
                flag = False
        else:
            print("用户帐号已被他人注册，请重新输入或者按Q退出注册程序")
            choice = input("Please enter choice:  ").strip()
            if choice in {'Q','q'}:
                flag = False
def UserLogin(retry=3):
    data = GetUserData()
    while retry:
        username = input("请输入用户名： ").strip()
        password = input("请输入密码： ").strip()
        
        if username in data.keys() and password == data[username]["password"]:
            print("登录成功,准备进入功能界面")
            BankFunc(username)
            break
        else:
            print("帐号不匹配或者密码不对，请重试")
            retry = retry - 1
            
    else:
        print("多次输入帐号或者密码不匹配，系统锁定5秒")
        time.sleep(5)  # 5秒
                 
def BankFunc(username):
    # flag 好像没有用上吧？
    """
    if not num.isdigit():
            print("错误！！！，非数字输入")
    看下这个可以独立一个函数不?
    """
    flag = True
    msg  = """ 
    查询请按 1
    取款请按 2
    转帐请按 3
    退出请按 0
    """
    data = GetUserData()
    while True:
        print(msg)
        num = input("请按上面提示输入正确的数字: ")
        if not num.isdigit():
            print("错误！！！，非数字输入")
        else:
            if int(num)  == 1 :  # 查询
                print(f"你的用户名是{username}，你的当前余额是{data[username]['money']}")
                
            elif int(num)  == 2: # 取款
                m  = input("请输入你要取现的金额： ").strip()
                if not m.isdigit():
                    print("错误！！！，非数字输入")
                    continue
                else:
                    if 0<= int(m) < data[username]['money']:
                        data[username]['money'] -= int(m)
                        print("取现成功，取现金{}".format(m))
                        with open('Bank.txt','w') as f:
                            json.dump(data,f)
                    else:
                        print("取现金额错误")
                        continue
                        
            elif int(num)  == 3:  # 转帐
                user  = input("请输入你转帐的用户帐号（限本行）： ").strip()
                mm = input("请输入你要转帐的金额： ").strip()
                if not mm.isdigit():
                    print("错误！！！，非数字输入")
                    continue
                if user not in data.keys():
                    print("错误！！！，帐号不存在") 
                    continue
                if user == username:
                    print("不能给自己转帐")
                    continue
                if 0 > int(mm) or int(mm) > data[username]['money']:
                    print("转帐金额错误")
                    continue
                else:
                    print("准备转帐")
                    data[username]['money'] -= int(mm)
                    data[user]['money'] += int(mm)
                    print(f"帐户{username}转帐给{user}，金额{mm}")
                    with open('Bank.txt','w') as f:
                        json.dump(data,f)

            elif int(num)  == 0:
                print("用户选择退出")
                break
            else:
                print("输入数字不正确，请输入可用的正确数字")
                

        
        
            
def WriteData(*args):
    data = GetUserData()
    username,password,ID,Tel = args
    data[username] = {'password':password,"money":5000,"ID":ID,"Tel":Tel}
    print(" 准备写数据")
    with open('Bank.txt','w') as f:
        json.dump(data,f)
    
    print(" 数据写完成")

if not os.path.exists('Bank.txt'):
    UserInit()     

while True:
    msg = """
    *************************************
    欢迎光临中国银行:
    按数字 1 进行 登录
    按数字 2 进行 注册用户帐号
    按数字 0 退出程序
    *************************************
       
    """
    print(msg)
    num = input("请输入正确的数字:  ").strip()
    if not num.isdigit():
        print("检测到非数字输入，请重新输入正确的数字")
        continue
    else:
        n = int(num)
        if n  not in {1,2,0}:
            print("检测到非数字输入，请重新输入正确的数字")
            continue
        else:
            if n == 1:
                print("开始进行用户登录")
                UserLogin(retry=3)
            if n == 2:
                print("开始创建用户")
                CreateUserAccount()
            if n == 0:
                print("程序退出")
                break
                
